from fastapi import APIRouter, HTTPException, status, Request
from typing import Optional
from backend.schemas.user import UserCreate, UserOut, Token, UserLogin, RoleOut, PermissionOut
from backend.services.user_service import UserService
from backend.common.jwt import create_access_token
from backend.schemas.response import ResponseBase
from backend.services.login_history_service import LoginHistoryService

router = APIRouter()

@router.post("/login", response_model=ResponseBase[Token], summary="用户登录")
async def login(user: UserLogin, request: Request):
    """
    用户登录端点，只支持JSON格式
    请求格式：{"username": "admin", "password": "admin123"}
    """
    # 获取请求IP和用户代理
    ip_address = request.client.host if request.client else "unknown"
    user_agent = request.headers.get("user-agent", "unknown")
    
    # 验证用户
    user_obj = await UserService.get_user_by_username(user.username)
    if not user_obj or not UserService.verify_password(user.password, user_obj.hashed_password):
        # 记录失败登录
        if user_obj:
            await LoginHistoryService.create_login_history(
                user_id=user_obj.id,
                ip_address=ip_address,
                user_agent=user_agent,
                status="失败"
            )
        raise HTTPException(status_code=401, detail="用户名或密码错误")
    
    # 生成令牌
    token = await create_access_token(user_obj)
    
    # 记录成功登录
    await LoginHistoryService.create_login_history(
        user_id=user_obj.id,
        ip_address=ip_address,
        user_agent=user_agent,
        status="成功"
    )
    
    return ResponseBase[Token](data={"access_token": token, "token_type": "bearer"})

@router.post("/register", response_model=ResponseBase[UserOut], summary="用户注册")
async def register(user: UserCreate):
    """用户注册端点"""
    exist_user = await UserService.get_user_by_username(user.username)
    if exist_user:
        raise HTTPException(status_code=400, detail="用户名已存在")
    
    user_obj = await UserService.create_user(
        username=user.username, 
        password=user.password,
        email=user.email,
        name=user.name,
        role_ids=user.role_ids,
        status=user.status
    )
    
    # 获取包含角色信息的用户数据
    user_obj = await UserService.get_user_by_id(user_obj.id)
    
    # 转换角色数据为DTO格式
    roles = []
    for role in user_obj.roles:
        permissions = []
        for permission in role.permissions:
            permissions.append(PermissionOut(
                id=permission.id,
                name=permission.name,
                code=permission.code,
                description=permission.description,
                created_at=str(permission.created_at),
                updated_at=str(permission.updated_at)
            ))
        roles.append(RoleOut(
            id=role.id,
            name=role.name,
            code=role.code,
            description=role.description,
            permissions=permissions,
            created_at=str(role.created_at),
            updated_at=str(role.updated_at)
        ))
    
    return ResponseBase[UserOut](data=UserOut(
        id=user_obj.id,
        username=user_obj.username,
        name=user_obj.name,
        email=user_obj.email,
        roles=roles,
        status=user_obj.status,
        created_at=str(user_obj.created_at),
        updated_at=str(user_obj.updated_at)
    ))

@router.post("/token", response_model=Token, summary="获取访问令牌")
async def get_token(user: UserLogin, request: Request):
    """
    获取访问令牌端点（与/login功能相同，保持兼容性）
    请求格式：{"username": "admin", "password": "admin123"}
    """
    # 获取请求IP和用户代理
    ip_address = request.client.host if request.client else "unknown"
    user_agent = request.headers.get("user-agent", "unknown")
    
    # 验证用户
    user_obj = await UserService.get_user_by_username(user.username)
    if not user_obj or not UserService.verify_password(user.password, user_obj.hashed_password):
        # 记录失败登录
        if user_obj:
            await LoginHistoryService.create_login_history(
                user_id=user_obj.id,
                ip_address=ip_address,
                user_agent=user_agent,
                status="失败"
            )
        raise HTTPException(status_code=401, detail="用户名或密码错误")
    
    # 生成令牌
    token = await create_access_token(user_obj)
    
    # 记录成功登录
    await LoginHistoryService.create_login_history(
        user_id=user_obj.id,
        ip_address=ip_address,
        user_agent=user_agent,
        status="成功"
    )
    
    return {"access_token": token, "token_type": "bearer"}
